import socket
from threading import Thread
import time


class Chatter:
	def __init__(self, soc: socket.socket):
		"""
		初始化聊天窗实例，储存连接信息。
		:param soc: 服务器信息
		"""
		self._socket = soc

	def send(self):
		"""
		发送消息的实现端口。
		特别的，当输入结束指令quit时，将标记变量记为假，结束发送。
		"""
		time.sleep(0.5)
		while True:
			data = input()
			self._socket.send(data.encode('utf-8'))
			if data == 'quit':
				flag = False
				break

	def receive(self, thread: Thread):
		"""
		接收消息的实现端口。
		发送线程在其中启动，当无法再获取到有效内容时结束。
		:param thread: 发送消息的线程
		"""
		username = input('输入用户名称：')
		self._socket.send(username.encode('utf-8'))
		thread.start()
		while flag:
			try:
				data = self._socket.recv(1024).decode('utf-8')
				if not data:
					break
				print(data)
			except:
				break


if __name__ == "__main__":
	ip = '192.168.43.111'
	host = 2121
	# addrs = socket.getaddrinfo(socket.gethostname(), None)
	client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	# 启动连接用的网络服务
	try:
		client.connect((ip, host))
		flag = True
		chat = Chatter(client)
		send_t = Thread(target=Chatter.send, args=(chat,))
		recv_t = Thread(target=Chatter.receive, args=(chat, send_t))
		recv_t.start()
		recv_t.join()
		send_t.join()
	finally:
		print("连接关闭")
